package com.smart.common.config.datasource;

import com.alicp.jetcache.Cache;
import com.smart.common.entities.constant.SmartConstant;
import com.smart.common.entities.option.SelectOptionMap;
import com.smart.manager.system.repository.DictRepository;
import io.ebean.Database;
import io.ebean.DatabaseFactory;
import io.ebean.config.DatabaseConfig;
import io.ebean.spring.txn.SpringJdbcTransactionManager;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.List;

/**
 * Ebean 集成Springboot 数据配置
 *
 * @author Xiaxuqiu
 * @date 2022-08-09
 **/
@Component
@Log4j2
public class EbeanConfiguration {

    private DictRepository dictRepository;

    private Cache<String, List<SelectOptionMap>> dictCache;

    public void setTranslatorHandler(Cache<String, List<SelectOptionMap>> dictCache, DictRepository dictRepository) {
        this.dictRepository = dictRepository;
        this.dictCache = dictCache;
    }


    @Bean
    public Database createEbeanServer(DataSource dataSource) {

        DatabaseConfig config = new DatabaseConfig();

        config.setExternalTransactionManager(new SpringJdbcTransactionManager());
        //设置数据源
        config.setDataSource(dataSource);
        //设置扫描包的范围
        config.addPackage(SmartConstant.ROOT_PACKAGES);

        //设置查询请求拦截器 进行数据字典翻译
        EbeanDictPostLoad ebeanDictPostLoad = new EbeanDictPostLoad(this.dictRepository, this.dictCache);
        config.setPostLoaders(List.of(ebeanDictPostLoad));

        config.setChangeLogIncludeInserts(true);
        config.setCurrentUserProvider(new EbeanCurrentUserProvider());
        //是否执行建表SQL
        config.setDdlRun(false);
        //是否生成建表SQL
        config.setDdlGenerate(false);
        //是否跳过删表SQL
        config.setDdlCreateOnly(false);

        //注册雪花算法到Id生成器
        config.setIdGenerators(List.of(new EbeanIdGenerator()));
        return DatabaseFactory.create(config);
    }


}
